package managment;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;


/**
 * finished-tested
 * testing levetl: moderate(two test cases)
 * */
@SuppressWarnings("unchecked")
public class External extends ArraySource{

	BufferedReader br;
	File dir;
	File[] files;
	private boolean skipList;
	
	protected External(int arraySize, Object prmtr) throws FileException{
		super(arraySize, prmtr);
		dir=new File((String)prmtr);
		this.files=dir.listFiles();
		if(files==null)
			throw new FileException("The specified directory does not exist");
		else if(files.length==0)
			throw new FileException("No files exist in the specified directory");
	}
	
	
	@Override
	public ArrayList<Comparable[]> createTarget() {
		
		String temp="";
		int j=0;
		try{
			for(j=0;j<this.files.length;j++){
				
				Comparable[]crtList=new Comparable[(int)(files[j].length()+2)/3];
				
				this.br=new BufferedReader(new FileReader(files[j]));
				
				for (int i = 0; i < crtList.length; i++) {
					
					try{
						
						crtList[i]=new Integer(Integer.parseInt
							(temp=this.br.readLine()));
						
					}
					catch(NumberFormatException e){
						
						//skip if it is a white space or null
						if(temp!=null && temp.indexOf(' ')==-1 && temp.indexOf('\t')==-1 && !temp.equals("")){
							
							System.out.println("non-suitable entry at \"" +
									files[j].getName() + "\"");
							skipList=true;
							
						}
						
						if(skipList)
							break;
						
						else if(temp==null)//end fo file
							break;
						i--;
						
					}
					
				}
				if(skipList){
					skipList=false;
					super.product.remove(crtList);
					continue;
				}
				
				super.product.add(trim(crtList));
				
			}
		}catch(IOException e){
			System.out.println(e.toString());
		}
		
		
		return super.product;
	}
	
	private Comparable[] trim(Comparable[] crtList) {
		
		int lenIdx;
		for (lenIdx = 0; lenIdx < crtList.length; lenIdx++) {
			if(crtList[lenIdx]==null)
				break;
		}
		Comparable[] clean=new Comparable[lenIdx];
		System.arraycopy(crtList, 0, clean, 0, lenIdx);
		return clean;
	}

	private class FileException extends ArraySource.MyException{

		private static final long serialVersionUID = 1L;

		protected FileException(String msg) {
			super(msg);
		}

		@Override
		public void handle() {
			// TODO Auto-generated method stub
			//this method will update the GUI
			System.out.println(super.msg);
		}
		
	}

}
